// draggable.js
export default {
  mounted(el, binding) {
    const state = {
      isDragging: false,
      startX: 0,
      startY: 0
    };

    // 初始化样式
    Object.assign(el.style, {
      cursor: 'move',
      position: 'fixed',
      userSelect: 'none',
      ...Object.entries(binding.value || {}).reduce((acc, [key, val]) => {
        acc[key] = typeof val === 'number' ? `${val}px` : val;
        return acc;
      }, {})
    });

    // 阻止滚动方法
    const preventScroll = e => {
      e.preventDefault();
      e.stopPropagation();
    };

    // 滚动锁定方法
    const lockScroll = () => {
      document.body.style.overflow = 'hidden';
      document.documentElement.style.overscrollBehavior = 'none';
      document.body.style.touchAction = 'none';
    };

    const unlockScroll = () => {
      document.body.style.overflow = '';
      document.documentElement.style.overscrollBehavior = '';
      document.body.style.touchAction = '';
    };

    // 移动处理（修正后的代码）
    const moveHandler = e => {
      if (!state.isDragging) return;
      e.preventDefault();

      const point = e.touches?.[0] || e;
      const maxX = document.documentElement.clientWidth - el.offsetWidth;
      const maxY = document.documentElement.clientHeight - el.offsetHeight;

      const newX = Math.max(0, Math.min(
        point.pageX - state.startX,
        maxX
      ));
      
      const newY = Math.max(0, Math.min(
        point.pageY - state.startY,
        maxY
      ));

      el.style.left = `${newX}px`;
      el.style.top = `${newY}px`; // ✅ 修正后的字符串拼接
    };

    // 开始拖拽
    const startHandler = e => {
      state.isDragging = true;
      lockScroll();

      const point = e.touches?.[0] || e;
      state.startX = point.pageX - el.offsetLeft;
      state.startY = point.pageY - el.offsetTop;

      document.addEventListener('mousemove', moveHandler);
      document.addEventListener('touchmove', moveHandler, { passive: false });
      document.addEventListener('mouseup', endHandler, { once: true });
      document.addEventListener('touchend', endHandler, { once: true });
    };

    // 结束拖拽
    const endHandler = () => {
      state.isDragging = false;
      unlockScroll();
      
      document.removeEventListener('mousemove', moveHandler);
      document.removeEventListener('touchmove', moveHandler);
    };

    // 事件绑定
    el.addEventListener('mousedown', startHandler);
    el.addEventListener('touchstart', startHandler, { passive: false });

    // 清理
    el._cleanDrag = () => {
      document.removeEventListener('mousemove', moveHandler);
      document.removeEventListener('touchmove', moveHandler);
    };
  },

  unmounted(el) {
    el._cleanDrag?.();
  }
};